package net.mikoo.seals.agent.web.controller;


import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.mikoo.seals.agent.biz.services.CompanyServices;
import net.mikoo.seals.agent.biz.services.DevicesServices;
import net.mikoo.seals.agent.common.BaseController;
import net.mikoo.seals.agent.common.PageModel;
import net.mikoo.seals.agent.common.exception.ParametersException;
import net.mikoo.seals.agent.model.Company;
import net.mikoo.seals.agent.model.CompanyQuery;
import net.mikoo.seals.agent.model.Devices;
import net.mikoo.seals.agent.model.DevicesQuery;



@Controller
@RequestMapping("/admin/devices")
public class DevicesController extends BaseController {
	
	Logger logger = LoggerFactory.getLogger(DevicesController.class);
	
	@Autowired
	private DevicesServices devicesServices;
	
	@Autowired
	private CompanyServices companyServices;
	
	@RequestMapping("/list")
	public String list(DevicesQuery query, HttpServletRequest request, Model model) {
		PageModel<Devices> pm  = devicesServices.getPageByQuery(query);
		model.addAttribute("pm", pm);
		model.addAttribute("query", query);
		return resultView(ADMIN_VIEW, "devices/list");
	}
	

	@RequestMapping("/form")
	public String form(Model model) {
		
		CompanyQuery query  = new CompanyQuery();
		
		List<Company> companys =  companyServices.getListByQuery(query);
		model.addAttribute("companys", companys);
		
		return resultView(ADMIN_VIEW, "devices/form");
	}
	
	
	@RequestMapping("/create")
	@ResponseBody
	public Map<String,Object> create(Devices devices,HttpServletRequest request, Model model) {
		try {
			
			
			devicesServices.save(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
	}

	@RequestMapping("/edit")
	public String edit(Long devicesId, Model model) {
		Devices devices = devicesServices.getInfoById(devicesId);
		model.addAttribute("devices", devices);
		return resultView(ADMIN_VIEW, "devices/edit");
	}
	
	
	@RequestMapping("/modify")
	public Map<String,Object> modify(Devices devices, Model model) {
		
		try {
			devicesServices.modify(devices);
			return result(SUCCESS, "添加成功");
		}catch (ParametersException e) {
			logger.error("",e);
			return result(ERROR, e.getMessage());
		}catch (Exception e) {
			logger.error("",e);
			return result(ERROR, "系统出错");
		}
		
		
	}

}
